<template>
  <el-dialog
    :title="isEdit ? '编辑商品' : '新增商品'"
    v-model="visible"
    width="600px"
    @close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="商品名称" prop="goodName">
        <el-input v-model="form.goodName" placeholder="请输入商品名称" />
      </el-form-item>
      
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model="form.shopName" placeholder="请输入店铺名称" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
           <el-form-item label="库存" prop="stock">
            <el-input-number v-model="form.stock" :min="0" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品类型">
            <el-select v-model="form.goodType" placeholder="请选择类型" style="width: 100%">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="审核状态">
        <el-radio-group v-model="form.authType">
          <el-radio :value="1">已审核</el-radio>
          <el-radio :value="0">未审核</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="商品图片" prop="goodPic">
        <el-input v-model="form.goodPic" placeholder="请输入图片URL" />
        <!-- 简单的图片预览 -->
        <div v-if="form.goodPic" class="image-preview">
          <img :src="form.goodPic" alt="preview" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'

const props = defineProps({
  visible: Boolean,
  isEdit: Boolean,
  goodData: Object,
  loading: Boolean, // 接收父组件的 loading 状态
  categoryList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:visible', 'success'])

const visible = ref(props.visible)
const formRef = ref()

// 表单数据
const form = reactive({
  goodName: '',
  shopName: '',
  stock: 0,
  goodType: 1,
  authType: 1,
  goodPic: '',
  exist: 1
})

// 验证规则
const rules = reactive({
  goodName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  shopName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
})

// 监听 visible 变化，同步内部 visible
watch(() => props.visible, (val) => {
  visible.value = val
})

// 监听内部 visible 变化，通知父组件
watch(visible, (val) => {
  emit('update:visible', val)
  if (!val) {
    handleClose()
  }
})

// 监听 goodData 变化，进行回显或重置
watch(() => props.goodData, (val) => {
  if (props.isEdit && val) {
    Object.assign(form, {
      goodName: val.goodName,
      shopName: val.shopName,
      stock: val.stock,
      goodType: val.goodType,
      authType: val.authType,
      goodPic: val.goodPic,
      exist: val.exist
    })
  } else {
    // 新增模式或无数据时重置
    resetForm()
  }
}, { immediate: true, deep: true })

// 额外的重置逻辑，确保每次打开新增都是空的
watch(() => props.visible, (val) => {
  if (val && !props.isEdit) {
    resetForm()
  }
})

function resetForm() {
  form.goodName = ''
  form.shopName = ''
  form.stock = 0
  form.goodType = 1
  form.authType = 1
  form.goodPic = ''
  form.exist = 1
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleClose = () => {
  // 实际上 el-dialog 的 close 事件会触发这里，或者点击取消
  // 这里我们只需要确保 emit false 即可，上面 watch visible 已经处理了 emit
  // 主要是重置表单
  // resetForm() // 不需要在这里强制重置，因为下次打开会重置，或者 goodData 变化会重置
  // 但是为了保险，可以清理验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // 复制一份数据传给父组件
      emit('success', { ...form })
    }
  })
}
</script>

<style scoped>
.image-preview {
  margin-top: 10px;
  width: 100px;
  height: 100px;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}
.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>

